package com.gton.handler;


import cn.dev33.satoken.stp.StpUtil;
import com.gton.common.ContextCommonMsg;
import com.gton.common.NeedTokenByJWT;
import com.gton.common.SkipTokenByJWT;
import com.gton.config.NotLoginException;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;

/**
 * @description: 授权认证：HandlerInterceptor需要注册拦截地址哦！！！
 * @author: GuoTong
 * @createTime: 2022-11-05 15:40
 * @since JDK 1.8 OR 11
 **/
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        //  获取当前会话是否已经登录，返回true=已登录，false=未登录
        String requestURI = httpServletRequest.getRequestURI();
        // 判断是否是认证中心对外认证接口
        if (requestURI.contains("/sso")) {
            return true;
        }

        // 如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();
        //检查是否有SkipTokenByJWT注释，有则跳过认证
        if (method.isAnnotationPresent(SkipTokenByJWT.class)) {
            SkipTokenByJWT SkipTokenByJWT = method.getAnnotation(SkipTokenByJWT.class);
            if (SkipTokenByJWT.required()) {
                return true;
            }
        }
        // 否则需要登陆
        if (!StpUtil.isLogin()) {
            throw new NotLoginException(ContextCommonMsg.ERROR_MSG_4);
        }
        //检查有没有需要用户权限的注解
        if (method.isAnnotationPresent(NeedTokenByJWT.class)) {
            NeedTokenByJWT needTokenByJWT = method.getAnnotation(NeedTokenByJWT.class);
            if (needTokenByJWT.required()) {
                List<String> permissionList = StpUtil.getPermissionList();
                // 查看当前用户是否包含当前接口的权限
                if (!permissionList.contains(needTokenByJWT.rule())) {
                    throw new NotLoginException(ContextCommonMsg.ERROR_MSG_3);
                }
            }
        }
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest httpServletRequest,
                           HttpServletResponse httpServletResponse,
                           Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {
    }

}